package com.itbaizhan.shopping_order_service.service.impl;

import com.itbaizhan.shopping_common.pojo.CartGoods;
import com.itbaizhan.shopping_common.pojo.DomainEvent;
import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.service.OrderService;
import com.itbaizhan.shopping_order_service.mapper.CartGoodsMapper;
import com.itbaizhan.shopping_order_service.mapper.OrderMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@DubboService
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartGoodsMapper cartGoodsMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void add(Orders orders) {
        // 设置订单状态为未付款
        if (orders.getStatus() == null) {
            orders.setStatus(1);
        }

        // 设置订单创建时间
        orders.setCreateTime(new Date());
        // 计算订单价格
        List<CartGoods> cartGoods = orders.getCartGoods();
        BigDecimal sum = BigDecimal.ZERO;
        for (CartGoods cartGood : cartGoods) {
            sum = sum.add(cartGood.getPrice().multiply(new BigDecimal(cartGood.getNum())));
        }
        orders.setPayment(sum);
        // 添加订单
        orderMapper.insert(orders);
        // 将购物车中的数据保存到数据库
        for (CartGoods cartGood : cartGoods) {
            cartGood.setOrderId(orders.getId());
            cartGoodsMapper.insert(cartGood);
        }

        //删除redis中的购物车数据
        for (CartGoods cartGood : cartGoods) {
            DomainEvent event = new DomainEvent();
            event.setEventType("del_cart"); //事件为下架
            event.setData(cartGood.getGoodId() + "#" + orders.getUserId());
            rocketMQTemplate.syncSend("cart_event_topic", event);
        }
        rocketMQTemplate.syncSend("check_orders_queue", MessageBuilder.withPayload(orders.getId()).build(), 15000, 4);
    }

    @Override
    public void update(Orders orders) {
        orderMapper.updateById(orders);
    }

    @Override
    public Orders findById(String id) {
        return orderMapper.findById(id);
    }

    @Override
    public List<Orders> findByUserId(Long userId, Integer status) {

        return orderMapper.findByUserId(userId, status);
    }
}
